package com.cashmate.struts;

import com.cashmate.hibernate.dao.AreaDAO;
import com.cashmate.hibernate.pojo.Areas;
import com.cashmate.hibernate.pojo.Employees;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

@Action(value = "/select-areas", results = {
    @Result(name = "success", location = "../fragments/areas.jsp"),
    @Result(name = "error", location = "../error/messages.jsp")
})
public class ForGridSelectAreas extends ActionSupport {

    private static Logger logger = Logger.getLogger(ForGridSelectAreas.class);
    private List<Areas> areases;
    private final AreaDAO areas = (AreaDAO) ServletActionContext.getServletContext().getAttribute("areaDAO");

    @Override
    public String execute() {
        try {
            DetachedCriteria criteria = criteria = DetachedCriteria.forClass(Areas.class);
            criteria.add(Restrictions.eq("isactive", true));
            int total = areas.countByCriteria(criteria);
            criteria.setProjection(null);
            criteria.setResultTransformer(Criteria.ROOT_ENTITY);
            criteria.addOrder(Order.asc("areacode"));
            areases = areas.findByCriteria(criteria, 0, total);
        } catch (Exception ex) {
            Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + ex.getLocalizedMessage(), ex);
            } else {
                logger.fatal(ex.getLocalizedMessage(), ex);
            }
            addActionError(ex.getLocalizedMessage());
            return ERROR;
        }
        return SUCCESS;
    }

    public List<Areas> getAreases() {
        return areases;
    }
    
}
